#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
歌曲宝自动化下载脚本 - 简化快速版
"""

import os
import time
import urllib.parse
import glob
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementNotInteractableException
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('download_log.txt', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class GequbaoDownloaderSimple:
    def __init__(self, download_path=None):
        """初始化下载器"""
        self.download_path = download_path or os.path.join(os.getcwd(), 'downloads')
        if not os.path.exists(self.download_path):
            os.makedirs(self.download_path)
        
        self.driver = None
        self.wait = None
        
    def setup_driver(self):
        """设置Chrome浏览器驱动"""
        try:
            logger.info("初始化浏览器...")
            
            options = Options()
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--disable-popup-blocking')
            
            # 设置下载选项
            prefs = {
                "download.default_directory": self.download_path,
                "download.prompt_for_download": False,
                "download.directory_upgrade": True,
                "safebrowsing.enabled": False,
            }
            options.add_experimental_option("prefs", prefs)
            
            # 使用Homebrew chromedriver
            chromedriver_path = "/opt/homebrew/bin/chromedriver"
            if os.path.exists(chromedriver_path):
                service = Service(chromedriver_path)
                self.driver = webdriver.Chrome(service=service, options=options)
            else:
                self.driver = webdriver.Chrome(options=options)
            
            self.wait = WebDriverWait(self.driver, 10)
            logger.info("✅ 浏览器初始化成功")
            return True
            
        except Exception as e:
            logger.error(f"浏览器初始化失败: {e}")
            return False
    
    def download_song(self, song_name):
        """处理单首歌曲：解析并返回 mp3 链接而不进行下载"""
        logger.info(f"🎵 开始处理: {song_name}")
        
        try:
            # 1. 搜索歌曲
            search_url = f"https://www.gequbao.com/s/{urllib.parse.quote(song_name)}"
            self.driver.get(search_url)
            time.sleep(3)
            
            # 2. 点击第一个播放&下载链接
            play_links = self.driver.find_elements(By.XPATH, "//a[contains(@href, '/music/') and .//u[contains(text(), '播放&下载')]]")
            if not play_links:
                logger.error(f"❌ 未找到 {song_name} 的搜索结果")
                return None
            
            # 跳转到音乐详情页
            music_url = play_links[0].get_attribute("href")
            self.driver.get(music_url)
            time.sleep(3)
            
            # 2.5 解析标题，尽力获取歌手与歌曲名
            title_text = self.driver.title or ""
            artist = ""
            track_title = song_name
            parts = [p.strip() for p in title_text.split("-") if p.strip()]
            if len(parts) >= 2:
                # 常见：歌曲名 - 歌手 - 站点 或 歌手 - 歌曲名 - 站点
                if song_name and song_name in parts[0]:
                    track_title = parts[0]
                    artist = parts[1]
                else:
                    artist = parts[0]
                    track_title = parts[1]
            display_name = f"{artist} - {track_title}" if artist else track_title
            
            # 3. 点击下载歌曲按钮，展开下载链接
            download_btn = self.driver.find_element(By.ID, "btn-download-mp3")
            download_btn.click()
            time.sleep(2)
            
            # 4. 查找低品质MP3链接并提取 href
            mp3_links = self.driver.find_elements(By.XPATH, "//a[contains(@download, '.mp3')]")
            if mp3_links:
                mp3_url = mp3_links[0].get_attribute("href")
                logger.info("✅ 已获取MP3链接")
                return {"name": display_name, "url": mp3_url}
            else:
                logger.warning("⚠️ 未找到MP3下载链接")
                return None
            
        except Exception as e:
            logger.error(f"❌ 处理 {song_name} 失败: {e}")
            return None
    
    def wait_and_rename(self, song_name, artist, before_files):
        """已废弃：保留占位以避免破坏外部调用"""
        logger.warning("该方法已废弃，无实际操作")
        return False
    
    def batch_download(self, songs_file):
        """批量处理并输出 JSON 清单"""
        if not self.setup_driver():
            return
        
        try:
            with open(songs_file, 'r', encoding='utf-8') as f:
                content = f.read().strip()
                # 使用正则表达式提取【】中的歌曲名称
                import re
                songs = re.findall(r"【([^】]+)】", content)
                songs = [song.strip() for song in songs if song.strip()]
            
            logger.info(f"📋 共 {len(songs)} 首歌曲待处理")
            results = []
            
            for i, song in enumerate(songs, 1):
                logger.info(f"📍 [{i}/{len(songs)}] 处理中...")
                info = self.download_song(song)
                if info:
                    results.append(info)
                if i < len(songs):
                    time.sleep(1.5)
            
            # 输出到与输入文件同名的 JSON 文件
            output_file = os.path.splitext(songs_file)[0] + ".json"
            with open(output_file, 'w', encoding='utf-8') as jf:
                json.dump(results, jf, ensure_ascii=False, indent=2)
            logger.info(f"🎯 处理完成，已写入: {output_file}，共 {len(results)} 条")
            
        except Exception as e:
            logger.error(f"批量处理失败: {e}")
        finally:
            input("按回车键关闭浏览器...")
            if self.driver:
                self.driver.quit()


def main():
    """主函数"""
    songs_file = "songs_list.txt"  # 改回使用完整的歌曲列表
    download_path = os.path.join(os.getcwd(), "downloads")
    
    if not os.path.exists(songs_file):
        logger.error(f"文件 {songs_file} 不存在")
        return
    
    downloader = GequbaoDownloaderSimple(download_path)
    logger.info("🚀 歌曲宝快速处理工具（输出JSON，不执行下载）")
    logger.info(f"📁 工作目录: {os.getcwd()}")
    downloader.batch_download(songs_file)


if __name__ == "__main__":
    main() 